<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button v-if="checkPermission('exportEmployee')" size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPermission('addEmployee')" size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="tableDate" style="width: 100%">

          <el-table-column label="序号" sortable="" type="index" width="150" />
          <el-table-column label="姓名" sortable="" prop="username" width="150" />
          <el-table-column label="头像" sortable="" width="150" align="center">
            <template #default="{row}">
              <el-avatar :size="100" src="https://empty">
                <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" fit="cover" @click="showAvatarImg(row.staffPhoto)">
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="手机号" sortable="" prop="mobile" width="150" />
          <el-table-column label="工号" sortable="" prop="workNumber" width="150" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" width="200" />
          <el-table-column label="部门" sortable="" prop="departmentName" width="150" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry" width="150">
            <!-- 插槽的开始 -->
            <template #default="{row}">
              {{ row.timeOfEntry | timeData }}
            </template>
            <!-- 插槽的结束 -->
          </el-table-column>
          <el-table-column label="账户状态" sortable="" width="150">
            <!-- 使用插槽 -->
            <template #default="{row}">
              <el-switch
                :value="row.enableState === 2"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" sortable="" fixed="right" width="280" align="center">

            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="handleClick(row.id)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>

        <!-- 分页组件开始 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="page.total" :page-size="page.size" @current-change="changePage" />
        </el-row>
        <!-- 分页组件结束 -->

      </el-card>
      <el-dialog title="头像二维码" :visible="isShowAvatar" @close="isShowAvatar=false">
        <el-row type="flex" justify="center">
          <canvas ref="myAvatar" />
        </el-row>
      </el-dialog>
    </div>

    <!-- 引入弹窗开始 -->
    <add-employee :show-dialog="showDialog" @btnCancel="showDialog=false" @updata="getEmployee" />
    <!-- 引入弹窗结束 -->

    <!-- 角色弹窗组件开始 -->
    <assignrole ref="assignRole" :show-dialog="showAssignRole" :user-id="userId" @btnCancel="showAssignRole=false" />
    <!-- 角色弹窗组件结束 -->
  </div>
</template>

<script>
import QRCode from 'qrcode'
import { getEmployee, delEmployee } from '@/api/employees'
import addEmployee from './components/add-employee.vue'
import employees from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import assignrole from './components/assign-role.vue'
export default {
  components: { addEmployee, assignrole },
  data() {
    return {
      // table表单数据
      tableDate: [],
      // 分页数据
      page: {
        page: 1,
        size: 8,
        total: 0
      },

      // 弹窗层的打开
      showDialog: false,
      isShowAvatar: false,
      showAssignRole: false,
      userId: ''
    }
  },
  // 初始化页面调用函数
  created() {
    this.getEmployee()
  },
  methods: {
    checkPermission(pointName) {
      return this.$store.getters.points.includes(pointName)
    },
    // 显示二维码
    showAvatarImg(url) {
      if (url) {
        this.isShowAvatar = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myAvatar, url, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 获取员工详细信息
    async getEmployee() {
      const res = await getEmployee(this.page)
      console.log(res)
      this.tableDate = res.rows
      this.page.total = res.total
      console.log(this.tableDate)
    },

    // 当前页发送改变
    changePage(newPage) {
      // 把点击的当前页赋值给变量
      this.page.page = newPage
      // 重新发送请求
      this.getEmployee()
    },

    formatEmployment(rol, column, cell, index) {
      // 枚举数据, 将所有可能性列举出来
      // 从外部文件引入
      // const hireType = [
      //   { id: 1, value: '正式工' },
      //   { id: 2, value: '临时工' },
      //   { id: 3, value: '实习生' }
      // ]
      // 要拿值的时候, 只需要, 查找当前的数组中 id === cell 那个对象
      // 输出 value 即可
      const obj = employees.hireType.find(item => item.id === cell)
      return obj ? obj.value : '未知'
    },

    // 点击删除时，删除员工
    async handleClick(id) {
      try {
        // // 1.提醒用户
        await this.$confirm(this.$t('questions.delEmployee'))
        // 2.发送删除数据
        await delEmployee(id)
        // 3.提示用户，删除成功
        this.$message.success('删除成功')
        // 判断是不是最后一条数据
        if (this.tableDate.length === 1 && this.page.page > 1) {
          this.page.page -= 1
        }
        // 4.刷新页面
        this.getEmployee()
        console.log(id)
      } catch (error) {
        console.log(error)
      }
    },

    // 点击导出时
    async   exportExcel() {
      const { rows } = await getEmployee({ page: 1, size: this.page.total })
      console.log(99, rows)
      // 根据生成 excel 插件需要，转换数据
      const header = [
        '手机号',
        '姓名',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      // 返回一个新数组
      const data = rows.map(userObj => {
        return this.obj2arr(userObj, header)
      })
      console.log(rows)
      console.log(data)
      // 调用函数
      export_json_to_excel({
        // header: ['姓名', '年龄', '性别'],
        // data: [
        //   ['tom', 12, '男'],
        //   ['rose', 13, '女']
        // ]
        header,
        data
      })
    },
    // 定义一个新的函数
    obj2arr(userObj, header) {
      const userArr = []
      // 将用户对象里面的数据
      // 按照表头的顺序, 逐个放入到数组中
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 存在一个新数组里面
      header.forEach(key => {
        const enKey = dict[key]
        let value = userObj[enKey]
        if (enKey === 'formOfEmployment') {
          // 如果是聘用形式, 用枚举数据处理
          const obj = employees.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 格式化日期
          value = formatDate(value)
        }
        userArr.push(value)
      })
      return userArr
    },

    // 点击角色进行弹窗
    async  assignRole(id) {
      // 把点击后的id传给子组件
      this.userId = id
      await this.$refs.assignRole.getCheckedRole(id)
      this.showAssignRole = true
    }
  }
}
</script>

<style>

</style>
